package com.shijie.newvideo.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.StateListDrawable;
import android.text.TextUtils;
import android.view.View;

/**
 * 提供一些与view有关的工具
 *
 * @author 刘汝寿
 * @date 2017/4/10.
 */
public class ViewUtils {

    /**
     * 通过一张正常或按下的背景资源，自动设置带按下效果的背景。
     * 可以免去麻烦地设置drawable资源。
     *
     * @param view  the view
     * @param resId the res id，默认支技“_sl”、“_n”和“_p”结尾的资源
     *              如果传“_n”会自动找“_p”的作为按下效果
     *              否则，比如“_s”，会自动找“_n”为正常效果
     */
    public static void setEffectiveBackground(View view, int resId) {
        if (view == null) {
            return;
        }
        Context context = view.getContext();
        Resources res = context.getResources();
        String resName = null;
        try {
            //完整的名字
            resName = res.getResourceName(resId);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
            return;
        }
        if (!TextUtils.isEmpty(resName)) {
            if (resName.endsWith("_sl")) {
                //已经是以sl结尾的，直接设置就好
                view.setBackgroundResource(resId);
            } else {
                int bg1 = 0;
                int bg2 = 0;
                if (resName.endsWith("_n")) {
                    bg1 = resId;
                    String resName2 = resName.substring(0, resName.length() - 2) + "_p";
                    bg2 = res.getIdentifier(resName2, null, null);
                } else {
                    //不以n结尾，需要正常
                    bg2 = resId;
                    String resName1 = resName.substring(0, resName.length() - 2) + "_n";
                    bg1 = res.getIdentifier(resName1, null, null);
                }
                if (bg1 == 0 || bg2 == 0) {
                    return;
                }

                //stateListDrawable
                StateListDrawable stateListDrawable = new StateListDrawable();
                stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, res.getDrawable(bg2));
                stateListDrawable.addState(new int[]{}, res.getDrawable(bg1));

                view.setBackgroundDrawable(stateListDrawable);
            }
        }
    }

    /**
     * 根据宽高比，考虑进padding，根据宽算出高。
     *
     * @param view   view
     * @param width  宽
     * @param whRate 宽高比，宽/高的比例
     * @return 计算出的高
     */
    public static int getAutoResizeHeight(View view, int width, float whRate) {
        if (view == null || whRate == 0) {
            return 0;
        }
        int w = width - view.getPaddingLeft() - view.getPaddingRight();
        //w/h=rate=w/h
        //h=w/rate
        int h = (int) (w / whRate);
        h += view.getPaddingTop() + view.getPaddingBottom();
        return h;
    }
}
